const puppeteer = require('puppeteer');
const axios = require('axios');
const nodemailer = require('nodemailer');
const requestArr = require('./config');
const amazonFn = require('./amazon');
const rakutenFn = require('./rakuten');

(async () => {

  let validArr = [];
  let _index = 0;

  for (const item of requestArr) {

    switch (item.type) {
      case 'amazon':
        try {
          const a_result = await amazonFn(item);
          if (a_result) {
            validArr.push(item)
          }
        } catch (e) {
          console.log(e)
        }
        break;
      case 'rakuten':
        try {
          const r_result = await rakutenFn(item);
          if (r_result) {
            validArr.push(item)
          }
        } catch (e) {
          console.log(e)
        }
        break;
    
      default:
        break;
    }

  }

  // jrywnywhlnksdifh

  const transporter = nodemailer.createTransport({
    host: "smtp.qq.com",
    port: 587,
    secure: false,
    auth: {
      user: "2306881717@qq.com", //我的邮箱
      pass: "jrywnywhlnksdifh", //授权码
    },
  });
  
  async function sendEMail(msg) {
    const info = await transporter.sendMail({
      from: "2306881717@qq.com",//发送人邮箱
      to: "1131096175@qq.com",//发送给谁
      subject: "你好",//标题
      text: msg,//内容
    });
  
    console.log("邮件发送成功：", info.messageId);
  }

  validArr.length > 0 ? sendEMail('任务已完成' + `${validArr?.reduce((pre, cur, idx, arr) => {
    return pre + `\r\n\r\n ${cur.name} --- ${cur.type} \r\n ${cur.url} \r\n`
  }, '')}`) : sendEMail('任务已完成，当前没有合适的购买项')

})();